package xyz.ibenben.zhongdian.common.util.example.easy;

import java.util.HashMap;
import java.util.Map;

/**
 * 给定一个正整数，返回它在 Excel 表中相对应的列名称。
 * <p>
 * 例如，
 * 1 -> A
 * 2 -> B
 * 3 -> C
 * ...
 * 26 -> Z
 * 27 -> AA
 * 28 -> AB
 * ...
 * 示例 1:
 * 输入: 1
 * 输出: "A"
 * 示例 2:
 * 输入: 28
 * 输出: "AB"
 * 示例 3:
 * 输入: 701
 * 输出: "ZY"
 */
public class ExcelTableRowName {
    public static void main(String[] args) {
        ExcelTableRowName etrn = new ExcelTableRowName();
        System.out.println(etrn.convertToTitle(260000));
        System.out.println(etrn.convertToTitle2(260000));
    }

    /**
     * 我给出的解决方案
     *
     * @param n
     * @return
     */
    public String convertToTitle(int n) {
        Map<Integer, String> map = new HashMap<>(26);
        map.put(1, "A");
        map.put(2, "B");
        map.put(3, "C");
        map.put(4, "D");
        map.put(5, "E");
        map.put(6, "F");
        map.put(7, "G");
        map.put(8, "H");
        map.put(9, "I");
        map.put(10, "J");
        map.put(11, "K");
        map.put(12, "L");
        map.put(13, "M");
        map.put(14, "N");
        map.put(15, "O");
        map.put(16, "P");
        map.put(17, "Q");
        map.put(18, "R");
        map.put(19, "S");
        map.put(20, "T");
        map.put(21, "U");
        map.put(22, "V");
        map.put(23, "W");
        map.put(24, "X");
        map.put(25, "Y");
        map.put(26, "Z");

        String result = "";
        while (n > 26) {
            int yu = n % 26;
            n /= 26;
            if (yu == 0) {
                yu = 26;
                n -= 1;
            }
            result = map.get(yu) + result;
        }
        result = map.get(n) + result;
        return result;
    }

    /**
     * 官网给出的解决方案
     *
     * @param n
     * @return
     */
    public String convertToTitle2(int n) {
        StringBuilder sb = new StringBuilder();
        while (n > 26) {
            int yu = n % 26;
            n = n / 26;
            if (yu == 0) {
                yu = 26;
                n = n - 1;
            }
            char letter = (char) (yu + 96);
            sb.insert(0, letter);
        }
        char letter = (char) (n + 96);
        sb.insert(0, letter);
        return sb.toString().toUpperCase();
    }
}
